#include <iostream>
#include <sstream>
#include "RTPPackage.hpp"
#include "StreamToMP4.hpp"
#include "RTPBufferReader.hpp"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <thread>

extern "C"
{
//编码
#include <libavcodec/avcodec.h>
//封装格式处理
#include <libavformat/avformat.h>
//像素处理
#include <libswscale/swscale.h>

#include <libavutil/mathematics.h>
#include <libavutil/time.h>

};

using namespace std;

int connect_socket(std::string ip, uint16_t port) {
    int sockfd = -1;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == sockfd) {
        perror("sock created");
        exit(-1);
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(struct sockaddr_in));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    int res = -1;
    res = connect(sockfd, (struct sockaddr *) &server, sizeof(server));
    if (-1 == res) {
        perror("sock connect");
        exit(-1);
    }

    return sockfd;
}

string bytes2HexString(unsigned char *data, int len) {
    stringstream ss;
    char temp[3];
    for (int i = 0; i < len; i++) {
        sprintf(temp, "%02x", data[i]);
        ss << temp;
    }
    return ss.str();
}


int main(int argc, char *argv[]) {

//    MP4Encoder mp4Encoder;
//    // convert H264 file to mp4 file
//    mp4Encoder.WriteH264File("test.264","test_f.mp4");
//    return 0;
    av_register_all();

    std::string ip_addr = argv[1];

    std::cout << "ip_addr: " << ip_addr << endl;

    uint16_t port = (uint16_t) stoi(argv[2]);

    std::cout << "port: " << port << endl;

    std::cout << "Start..." << std::endl;

    int sockfd = connect_socket(ip_addr, port);


    uint8_t socket_buffer[BUFFER_MAX] = {'\0'};

    RTPBufferReader  rtpb_reader;

    uint8_t request[7] = {0x01, 0x85, 0x91, 0x95, 0x05, 0x12,0x01};

    write(sockfd,request,7);
    while (true) {
        ssize_t read_len = read(sockfd, socket_buffer, 1024);
        if (read_len < 1) break;
        rtpb_reader.ReadBuffer(socket_buffer,read_len);
    }

    std::cout << "endl" << endl;
    return 0;
}